<template>
  <div class="Game" :style="bgStyle">

    <!--头区域-->
    <van-row>
      <van-col span="8" style="float: left;">
        <van-image style="margin: 10px;" round width="60px" height="60px" :src="avatar" />
        <span style="color: #fff;font-size: 30px;position: absolute;margin-top: 20px;">{{ score }}</span>
      </van-col>
      <van-col span="16" style="text-align: right; display: flex;padding: 20px;justify-content: flex-end;">
        <van-count-down ref="countDownRef" millisecond :time="time" format="ss:S" @finish="countDownFinish"
          v-if="time > 0 && answerTimeType != 0">
          <template #default="timeData">
            <span style="color: #fff;font-size: 14px;">时间：{{ timeData.minutes }}:{{ timeData.seconds }}</span>
          </template>
        </van-count-down>
        <span style="color: #fff;font-size: 14px; margin-left: 30px;">第{{ currentNum }}题/共{{ examQuestions }}题</span>
      </van-col>
    </van-row>

    <van-row style="margin-top: 10px;">
      <!--选项区域 但需那与多选题分开-->
      <van-radio-group v-if="question.questionType != 2" v-model="checked" style="width: 100%;">
        <van-cell-group inset>
          <van-cell :border="false">
            <template #title>
              <span style="font-weight: bold;font-size: 16px;">{{ `
                ${questionType[question.questionType]}：${question.ask}` }}</span>
            </template>
          </van-cell>
          <van-cell v-for=" (item, index) in question.buzTaskOptions"
            :title="`${item.character}` + ',' + `${item.content}`" clickable @click="onClickSelectAnswerRadio(item)">
            <template #label>
              <van-image width="50" height="50" :src="item.optionImg" v-if="item.optionImg" />
            </template>
            <template #right-icon>
              <van-radio :name="item.character" :disabled="showAnswer" />
            </template>
          </van-cell>
          <van-cell>
            <van-button size="large" type="primary" @click="next(checked)" style="margin-top: 15px;">下一题</van-button>
          </van-cell>
          <div v-if="showAnswer">
            <van-cell :border="false" title="正确答案：" :value="question.answerKey" />
            <van-cell :border="false" title="解析：" :label="question.questionMemo" />
          </div>
        </van-cell-group>
      </van-radio-group>

      <van-checkbox-group v-if="question.questionType == 2" v-model="checkboxed" style="width: 100%;">
        <van-cell-group inset>
          <van-cell :border="false">
            <template #title>
              <span style="font-weight: bold;font-size: 16px;">{{ `
                ${questionType[question.questionType]}：${question.ask}` }}</span>
            </template>
          </van-cell>
          <van-cell v-for="(item, index) in question.buzTaskOptions" clickable :key="item"
            :title="`${item.character}` + ',' + `${item.content}`" @click="toggle(index)">
            <template #label>
              <van-image width="50" height="50" :src="item.optionImg" v-if="item.optionImg" />
            </template>
            <template #right-icon>
              <van-checkbox :name="item.character" :ref="el => checkboxRefs[index] = el" :disabled="showAnswer"
                @click.stop />
            </template>
          </van-cell>
          <van-cell :border="false">
            <van-button size="large" type="primary" style="margin-top: 15px;"
              @click="nextcheckbox(checkboxed)">下一题</van-button>
          </van-cell>
          <div v-if="showAnswer">
            <van-cell :border="false" title="正确答案：" :value="question.answerKey" />
            <van-cell :border="false" title="解析：" :label="question.questionMemo" />
          </div>
        </van-cell-group>
      </van-checkbox-group>
    </van-row>
  </div>

  <van-overlay :show="show">
    <!--<van-image
                style="margin-top: 26%;position: absolute;margin-left: 20%;"
                width="250"
                height="250"
                src="https://fastly.jsdelivr.net/npm/@vant/assets/cat.jpeg"
            />-->
    <div class="wrapper">
      <van-cell-group inset style="width:340px">
        <van-cell style="text-align: center; width: 100%;height: auto;margin-top: 30px;">
          <div style="text-align: center;" v-if="canAwardsFlag == 1">
            <img v-if="appSetting.successfulChallenge && appSetting.successfulChallenge.successImg"
              :src="appSetting.successfulChallenge.successImg"
              style="max-width: 150px; max-height: 150px; margin: auto;cursor: pointer;">
            <img v-else :src="successCupImg" style="max-width: 150px; max-height: 150px; margin: auto;cursor: pointer;">
          </div>
          <div style="font-size: 20px;color:darkmagenta;text-align: center;">您的成绩为：{{ score }}分</div>
        </van-cell>
        <van-cell style="text-align: center; width: 100%;height: auto;" v-if="type != 'preactise'">
          <div style="font-size: 16px;color:black;text-align: center;" v-if="canAwardsFlag == 1">
            恭喜您获得1次抽奖机会，请立刻抽奖。
          </div>
          <div style="font-size: 16px;color:black;text-align: center;" v-if="canAwardsFlag == 0">
            遗憾您没能达到抽奖条件，再来一次。</div>
        </van-cell>
        <!-- <van-cell style="text-align: center; width: 100%;height: auto;">
                    <div style="font-size: 16px;color:black;text-align: center;">达到该成绩用时：{{ useTime }}秒</div>
                    <div style="font-size: 16px;color:black;text-align: center;">成功击败99%用户</div>
                </van-cell> -->
        <!--最佳成绩-->
        <!-- <van-cell>
                    <van-row style="text-align: center;font-size: 16px;color: blueviolet;">
                        <van-col span="8">最佳成绩</van-col>
                        <van-col span="8">最佳用时</van-col>
                        <van-col span="8">最佳排名</van-col>
                    </van-row>
                    <van-row style="text-align: center; color: brown;">
                        <van-col span="8">999分</van-col>
                        <van-col span="8">0秒</van-col>
                        <van-col span="8">NO.1</van-col>
                    </van-row>
                </van-cell> -->
        <!--今天的机会-->
        <!-- <van-cell>
                    <div style="font-size: 16px;color:black;text-align: center;">今天还有 {{ todayRemainTimes }}次机会</div>
                </van-cell> -->
        <van-cell v-if="type != 'preactise'">
          <van-button v-if="canAwardsFlag == 1"
            style="width: 100%;height: auto;font-size: 30px;background-color:blueviolet;color: #fff;"
            @click="onClickDraw">抽奖</van-button>
          <van-button v-else style="width: 100%;height: auto;font-size: 30px;background-color:blueviolet;color: #fff;"
            @click="againAnswer">再来一次</van-button>
        </van-cell>
        <van-cell v-else>
          <van-button style="width: 100%;height: auto;font-size: 30px;background-color:blueviolet;color: #fff;"
            @click="returnStart">返回首页</van-button>
        </van-cell>
      </van-cell-group>
    </div>
  </van-overlay>

  <van-popup v-model:show="giftBoxShow" :close-on-click-overlay="false">
    <div style="text-align: center;padding: 10px; font-size: 16px;">点击图片开始抽奖</div>
    <nutbig-giftbox ref="giftboxRef" @start-turns="" @end-turns="getAwards" />
  </van-popup>

  <van-dialog v-model:show="showPhoneDialog" title="领奖" :before-close="onBeforeClosePhoneDialog" @confirm="onConfirm">
    <van-form ref="formRef" style="margin-top: 20px;">
      <van-cell-group inset>
        <van-field v-model="form.mobile" name="mobile" label="手机号码" placeholder="请输入手机号码"
          :rules="[{ required: true, message: '请输入手机号码' }]" />
        <van-field name="code" v-model="form.code" center clearable label="短信验证码" placeholder="请输入短信验证码">
          <template #button>
            <van-button size="small" type="primary" :disabled="!sendCodeAble" @click="sendCode">
              <van-count-down ref="codeCountDownRef" :time="sendCodeTime" @finish="sendCodeAble = true">
                <template #default="timeData">
                  <span style="color: #fff;" v-if="sendCodeAble">获取验证码</span>
                  <span style="color: red;" v-if="!sendCodeAble">{{ timeData.seconds }}s</span>
                </template>
              </van-count-down>
              <span></span>
            </van-button>
          </template>
        </van-field>
      </van-cell-group>
    </van-form>
  </van-dialog>

  <van-popup v-model:show="showContactInfo">
    <ContactInfo @submit="onSubmitContactInfo" :noModify="detail.buzTask.contactInfoModify === 0 ? false : true" />
  </van-popup>

</template>
<script>
import { ref } from 'vue'
import { defineComponent } from 'vue';
import { useRoute } from 'vue-router';
import { getQuestion, getUserTaskAwards, saveUserTaskOption, sendSms, sendSms4Gain, submitSms4Gain, queryMemberInfo, getAppSetting, getAnswerByQuestionId, saveUserPraticTask, getCurrentDate } from '../api/task.js';
import { showDialog, showLoadingToast, closeToast, showFailToast } from 'vant';
import 'vant/es/dialog/style';
import { sampleSize } from 'lodash-es';
import ContactInfo from './ContactInfo.vue';
import successCupImg from '@/assets/images/successCupImg.png';

export default defineComponent({
  components: { ContactInfo },
  name: 'Game',
  props: ['id', 'type'],
  created() { },
  mounted() {
    this.getCanDate()
    this.getquestions()
    this.getAppSettings()
  },
  data() {
    return {
      showAnswer: false,
      sendCodeAble: true,
      sendCodeTime: 60000,
      form: {},
      showPhoneDialog: false,
      todayRemainTimes: 0, // 今日剩余抽奖次数
      giftBoxShow: false,
      "avatar": localStorage.getItem('avatar'),
      "buzTaskQuestions": [],
      "examQuestions": 0,
      "currentNum": 0,
      "question": {
        "id": 0,
        "ask": "",
        "buzTaskId": "",
        "aksImg": "",
        "questionType": 0,
        "buzTaskOptions": []
      },
      userAnwser: [],
      questionType: ['判断题', '单选题', '多选题'],
      show: false,
      startTime: new Date().getTime(),
      score: 0,
      questionPoints: 0,
      useTime: 0,
      time: 0,
      checked: undefined,
      checkboxRefs: ref([]),
      checkboxed: ref([]),
      buzTaskUserQuestions: [],
      buzTaskUserId: '',
      canAwardsFlag: null,
      taskUserId: '',
      answerTimeType: 0,
      showContactInfo: false,
      detail: {},
      appSetting: {},
      initAppSetting: {
        "home": {
          "bgStyle": {
            "backgroundColor": "#fff",
            "backgroundRepeat": "no-repeat",
            "backgroundSize": "100% 100%",
            // "backgroundImage": "url(https://s3.cn-north-1.jdcloud-oss.com/fkhd/微信截图_20230111155108_20231115094130A001.png)"
          }
        },
        "activeProcess": { "bgStyle": {} },
        "answerAnalysis": {},
        "successfulChallenge": {},
        "shareEffect": {}
      },
      getCorrectAnswer: false,
      canGiftDate: false
    }
  },
  computed: {
    bgStyle: function () {
      let tempBgStyle = this.initAppSetting.activeProcess.bgStyle;
      if (this.appSetting.activeProcess && this.appSetting.activeProcess.bgStyle) {
        tempBgStyle = { ...tempBgStyle, ...this.appSetting.activeProcess.bgStyle }
      }
      return tempBgStyle;
    }
  },
  methods: {
    getAppSettings() {
      getAppSetting({ taskId: this.id }).then(res => {
        if (res.code == 200) {
          this.appSetting = res.data;
        }
      })
    },
    onClickSelectAnswerRadio(item) {
      if (this.showAnswer) {
        return false;
      }
      this.checked = item.character;
    },
    onBeforeClosePhoneDialog(action, done) {
      // 点击了确定按钮
      if (action === "confirm") {
        return false;
      }
    },
    onSubmitContactInfo(e) {
      var that = this
      if (e) {
        this.showContactInfo = false;
        //事前修改完成
        if (this.detail.buzTask.contactInfo === 0 && this.detail.buzTask.contactInfoInput === 0) {
          // location.reload();
        }
        //事后修改完成
        else if (this.detail.buzTask.contactInfo === 0 && this.detail.buzTask.contactInfoInput === 1) {
          if (that.canGiftDate === true) {
            //that.giftBoxShow = true
            //新实现
            this.getMemberInfo(false,true)
          } else {
            showFailToast("抽奖时间未到，敬请期待")
            that.show = false
            that.showContactInfo = false
            setTimeout(() => {
              that.returnStart()
            }, 1000)
          }
        }
      }
    },
    getCanDate() {
      var that = this
      //时间检查
      this.canGiftDate = false
      // let canDate = new Date("2024-05-20")
      // await getCurrentDate("").then((res) => {
      //   if (res.code == 200) {
      //     that.canGiftDate = Date.parse(res.msg) >= Date.parse(canDate)
      //   }
      // })
    },
    onClickDraw() {
      var that = this
      //事后要填写信息
      if (that.detail.buzTask.contactInfo === 0 && that.detail.buzTask.contactInfoInput === 1) {
        that.getMemberInfo(true, true)
      } else if (that.detail.buzTask.contactInfo !== 0 || that.detail.buzTask.contactInfoInput !== 1) {
        //不是事后要填写
        if (that.type != 'preactise') {
          if (that.canGiftDate === true) {
            // that.giftBoxShow = true
            //新实现
            this.getMemberInfo(false,true)
          } else {
            showFailToast("抽奖时间未到，敬请期待")
            that.show = false
            that.showContactInfo = false
            setTimeout(() => {
              that.returnStart()
            }, 1000)
          }
        }
      }
    },
    getMemberInfo(needModify = false, isEnd = false) {
      var that = this
      queryMemberInfo({ openId: sessionStorage.getItem('token') }).then((res) => {
        if (res.code == 200) {
          //提前注入手机号
          that.form.mobile = res.data.phone;
          //需要修改
          if (needModify == true && !res.data.phone) {
            that.showContactInfo = true;
          } else {
            //应该只剩数据存在的情况
            if (that.type != 'preactise' && isEnd == true) {
              if (that.canGiftDate === true) {
                // that.giftBoxShow = true
                //新实现
                this.showPhoneDialog = true
              } else {
                showFailToast("抽奖时间未到，敬请期待")
                that.show = false
                that.showContactInfo = false
                setTimeout(() => {
                  that.returnStart()
                }, 1000)
              }
            }
          }
        }
      })
    },
    sendCode() {
      this.$refs.formRef.validate(['mobile']).then(() => {
        sendSms4Gain({
          mobile: this.form.mobile,
          mobileCode: 8888,
          taskId: this.id,
          taskUserId: this.taskUserId
        }).then((res) => {
          if (res.code == 200) {
            // todo 倒计时 不可点击 
            this.sendCodeAble = false;
            this.$refs.codeCountDownRef.reset();
          }
        })
      })
    },
    onConfirm() {
      // 提交手机号码和验证码
      var that = this
      localStorage.setItem('taskUserId', this.taskUserId)
      that.$refs.formRef.validate().then(() => {
        submitSms4Gain({
          mobile: that.form.mobile,
          code: that.form.code,
          taskId: that.id,
          taskUserId: that.taskUserId,
          openId: sessionStorage.getItem('token'),
          longitude: localStorage.getItem('longitude'),
          latitude: localStorage.getItem('latitude'),
          memberId: localStorage.getItem('token')
        }).then((res) => {
          that.showPhoneDialog = false;
          if (res.code == 200) {
            // todo 跳转红包链接
            // window.location.href = res.data.awardsUrl
            if (res.data.awardsLevel) {
              showDialog({
                title: '',
                message: `恭喜您中了${res.data.awardsLevel || ''}，奖品是：${res.data.awardName || ''}`,
                confirmButtonText: '去领奖'
              }).then(() => {
                that.goToAward()
              });
            } else {
              // 跳转未中奖页面
              showDialog({
                title: '',
                message: '很遗憾，没有中奖',
                confirmButtonText: '返回首页'
              }).then(() => {
                that.returnStart()
              });
            }
          }
        }).catch((err) => {
          that.showPhoneDialog = false;
          showDialog({
            title: '返回首页',
            message: err.message,
            confirmButtonText: '确定'
          }).then(() => {
            that.returnStart()
          });
        })
      })
    },
    getquestions() {
      // 获取经纬度信息

      const data = {};
      data.latitude = localStorage.getItem('latitude');
      data.longitude = localStorage.getItem('longitude');
      data.taskId = this.id;
      data.memberId = localStorage.getItem('token');
      data.preview = true;

      //获取题目信息
      getQuestion(data).then(res => {

        if (res.code == 500) {
          this.$router.back()
        } else {
          this.detail = res.data;

          // 判断是否要先填用户信息
          if (res.data.buzTask.contactInfo === 0 && res.data.buzTask.contactInfoInput === 0) {
            this.getMemberInfo(true, false)
          }

          // 题目总数
          this.examQuestions = res.data.buzTask.examQuestions;
          // this.buzTaskQuestions = res.data.buzTaskQuestions;
          this.buzTaskQuestions = sampleSize(res.data.buzTaskQuestions, this.examQuestions);
          this.buzTaskQuestions.map(e => {
            e.buzTaskOptions = e.buzTaskOptions.filter(e1 => e1.content || e1.optionImg)
          })
          // 每题分数
          this.questionPoints = res.data.buzTask.questionPoints;
          // 初始化第一题
          this.question = this.buzTaskQuestions[0];
          this.currentNum = 1;
          this.buzTaskUserId = res.data.buzTaskUser.id;
          this.time = res.data.buzTask.limitTimes * 1000;
          this.answerTimeType = res.data.buzTask.answerTimeType;


        }
      })
    },
    submit() {
      showLoadingToast({
        message: '加载中...',
        forbidClick: true,
      });
      this.getCanDate()
      const data = {};
      const buzTaskUser = {};
      var buzTaskUserQuestions = [];
      const buzTask = {};
      //活动信息
      buzTask.id = this.id;
      //用户信息
      buzTaskUser.id = this.buzTaskUserId;
      buzTaskUser.taskId = this.id;
      buzTaskUser.startTime = this.startTime;
      buzTaskUser.endTime = new Date().getTime();
      // 答题情况
      buzTaskUserQuestions = this.buzTaskQuestions;
      data.buzTask = buzTask;
      data.buzTaskUser = buzTaskUser;
      data.buzTaskUserQuestions = buzTaskUserQuestions;
      if (this.type == 'preactise') {
        saveUserPraticTask(data).then(res => {
          closeToast();
          this.show = true
          this.canAwardsFlag = res.data.canAwardsFlag
          this.taskUserId = res.data.id
          this.todayRemainTimes = res.data.todayRemainTimes
        }).catch((error) => {
          closeToast();
        })
      } else {
        saveUserTaskOption(data).then(res => {
          closeToast();
          this.show = true
          this.canAwardsFlag = res.data.canAwardsFlag
          this.taskUserId = res.data.id
          this.todayRemainTimes = res.data.todayRemainTimes
        }).catch((error) => {
          closeToast();
        })
      }
    },
    async next(character, isAuto = false) {
      if (!character && !isAuto) return false;

      if (this.answerTimeType == 2) {
        this.$refs.countDownRef.reset()
      }

      if (!this.getCorrectAnswer) {
        // 请求获取正确答案
        if (isAuto === false) {
          await getAnswerByQuestionId({ id: this.question.id }).then(res => {
            if (res.code == 200) {
              this.question.answerKey = res.msg
              if (character != res.msg) {
                this.showAnswer = true;
              } else {
                this.showAnswer = false
              }
              this.getCorrectAnswer = true
            }
          })
          if (this.showAnswer) {
            return false;
          }
        }
      } else {
        this.showAnswer = false;
      }
      if (isAuto === true) {
        this.showAnswer = false
        this.question.answerKey = ""
        this.$forceUpdate()
      }
      this.getCorrectAnswer = false
      //记录用户答案
      //下一题
      // 保存用户答案
      this.buzTaskQuestions[this.currentNum - 1].userAnswer = character
      const selectItem = this.buzTaskQuestions[this.currentNum - 1].buzTaskOptions.find(item => item.character === character)
      // 重新构筑对象
      const selectItemData = {};
      selectItemData.buzTaskUserId = this.buzTaskUserId;
      selectItemData.buzTaskId = this.id;
      selectItemData.buzTaskQuestionId = this.buzTaskQuestions[this.currentNum - 1].id;
      selectItemData.buzTaskOptionId = selectItem ? selectItem.id : "";
      selectItemData.character = selectItem ? selectItem.character : "";
      selectItemData.content = selectItem ? selectItem.content : "";
      selectItemData.optionImg = selectItem ? selectItem.optionImg : "";
      const buzTaskUserOptions = [];
      buzTaskUserOptions.push(selectItemData)
      this.buzTaskQuestions[this.currentNum - 1].buzTaskUserOptions = buzTaskUserOptions;


      this.userAnwser.push(character)
      // 判断是否是最后一题
      if (this.currentNum == this.examQuestions) {
        // 最后一题
        // 计算成绩
        if (character != '' && character == this.buzTaskQuestions[this.currentNum - 1].answerKey) {
          this.score += this.questionPoints;
        }
        // 显示成绩
        // 计算用时
        this.useTime = (new Date().getTime() - this.startTime) / 1000;
        this.submit()
      } else {
        // 不是最后一题
        // 显示下一题
        if (character != '' && character == this.buzTaskQuestions[this.currentNum - 1].answerKey) {
          this.score += this.questionPoints;
        }
        this.currentNum++
        this.question = this.buzTaskQuestions[this.currentNum - 1];
      }

      this.checked = undefined;

    },
    countDownFinish() {
      // 倒计时结束
      console.log('倒计时结束')
      // this.useTime = (new Date().getTime() - this.startTime)/1000;
      if (this.answerTimeType == 2) {
        if (this.show != true) {
          if (this.question.questionType != 2) {
            this.next("", true)
          } else {
            this.nextcheckbox([""], true)
          }
        }
      } else {
        if (this.show != true) {
          //暂时手动指定，不进行提交
          this.canAwardsFlag = 0
          this.show = true
          // this.buzTaskQuestions.map((item,index) => {
          //   if(index >= (this.currentNum -1)){
          //     item.answerKey = ""
          //     item.userAnswer = ""
          //   }
          // })
          // this.submit()
        }
      }


    },
    toggle(index) {
      if (this.showAnswer) {
        return false;
      }
      console.log('toggle')
      this.checkboxRefs[index].toggle()
    },
    async nextcheckbox(checkboxed, isAuto = false) {
      var character = "";
      checkboxed = checkboxed.sort((a, b) => a.charCodeAt() - b.charCodeAt())
      character = checkboxed.join('')
      console.log(character)
      if (this.answerTimeType == 2) {
        this.$refs.countDownRef.reset()
      }

      if (!this.getCorrectAnswer) {
        if (isAuto === false) {
          console.log(this.question, 'question');
          await getAnswerByQuestionId({ id: this.question.id }).then(res => {
            console.log(res, 'res');
            if (res.code == 200) {
              this.question.answerKey = res.msg
              if (character != res.msg) {
                this.showAnswer = true;
              } else {
                this.showAnswer = false
              }
              this.getCorrectAnswer = true
            }
          })
          if (this.showAnswer) {
            return false;
          }
        }

      } else {
        this.showAnswer = false;
      }
      if (isAuto === true) {
        this.showAnswer = false
        this.question.answerKey = ""
        this.$forceUpdate()
      }
      this.getCorrectAnswer = false
      // 保存用户答案
      this.buzTaskQuestions[this.currentNum - 1].userAnswer = character
      const buzTaskUserOptions = [];
      // 选项的答案
      this.buzTaskQuestions[this.currentNum - 1].buzTaskOptions.forEach(item => {
        if (checkboxed.includes(item.character)) {
          // 重新构筑对象
          const itemData = {};
          itemData.buzTaskUserId = this.buzTaskUserId;
          itemData.buzTaskId = this.id;
          itemData.buzTaskQuestionId = this.buzTaskQuestions[this.currentNum - 1].id;
          itemData.buzTaskOptionId = item.id;
          itemData.character = item.character;
          itemData.content = item.content;
          itemData.optionImg = item.optionImg;
          buzTaskUserOptions.push(itemData)
        }
      })

      this.buzTaskQuestions[this.currentNum - 1].buzTaskUserOptions = buzTaskUserOptions
      this.userAnwser.push(character)

      this.checkboxed = [];

      // 判断是否是最后一题
      if (this.currentNum == this.examQuestions) {
        // 最后一题
        // 计算成绩
        if (character != '' && character == this.buzTaskQuestions[this.currentNum - 1].answerKey) {
          this.score += this.questionPoints;
        }
        // 显示成绩
        // 计算用时
        this.useTime = (new Date().getTime() - this.startTime) / 1000;
        this.submit()
      } else {
        // 不是最后一题
        // 显示下一题
        if (character != '' && character == this.buzTaskQuestions[this.currentNum - 1].answerKey) {
          this.score += this.questionPoints;
        }
        this.currentNum++
        this.question = this.buzTaskQuestions[this.currentNum - 1];
      }
    },
    //抽奖
    getAwards() {
      const data = {};
      data.taskId = this.id;
      data.longitude = localStorage.getItem('longitude');
      data.latitude = localStorage.getItem('latitude');
      data.preview = true;
      data.taskUserId = this.taskUserId;
      data.memberId = localStorage.getItem('token');

      localStorage.setItem('taskUserId', this.taskUserId)
      getUserTaskAwards(data).then(res => {

        if (res.code == 200) {
          if (res.data.awardsLevel) {
            // 跳转中奖页面
            // this.$router.push('/redPacket?userTaskId=' + res.data.id)

            showDialog({
              title: '',
              message: `恭喜您中了${res.data.awardsLevel || ''}，奖品是：${res.data.awardName || ''}`,
              confirmButtonText: '立即领奖'
            }).then(() => {
              // this.$router.push('/redPacket?userTaskId=' + res.data.id)
              // this.showPhoneDialog = true;
              let url = `http://${location.host}/getAward`;
              location.href = `https://www.yaoyaola.net/exapi/check_user/10810602?url=${url}&flag=0`
            });

          } else {
            // 跳转未中奖页面
            showDialog({
              title: '',
              message: '很遗憾，没有中奖',
              confirmButtonText: '返回首页'
            }).then(() => {
              this.returnStart()
            });
          }
        }
      }).catch((err) => {
        showDialog({
          title: '返回首页',
          message: err.message,
          confirmButtonText: '确定'
        }).then(() => {
          this.returnStart()
        });
      })
    },
    returnStart() {
      this.$router.replace(`/index/${this.id}`)
    },
    againAnswer() {
      var id = this.id
      this.$router.replace({ path: '/empty', query: { origin: 'answer', path: "/answer", id: id } })
    },
    goToAward(){
      let url = `http://${location.host}/getAward`;
      location.href = `https://www.yaoyaola.net/exapi/check_user/10810602?url=${url}&flag=0`
    }
  },
})

</script>
<style lang="less">
.Game {
  width: 100%;
  min-height: 100vh;
  padding-bottom: 20px;
  // min-height: 750px;
  //display: flex;
  background: url(../assets/images/gameBg.jpg) no-repeat;
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  width: 100%;
  flex-direction: column;
}

.block {
  height: 120px;
  //background-color: #fff;
}
</style>